<template>
  <Dialog
    :funcConfirm="handleConfirm"
    :funcCancel="handleClose"
    :headerTitle="headerTitle"
    :confirmTitle="confirmTitle"
    :open="open"
  >
    <template v-slot:body>
      <div class="content-wrapper">
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{'*'}}</span>
            <span class="name-text">{{"名 称："}}</span>
          </div>
          <div class="input-box">
            <input type="text" v-model="params.name" maxlength="20" minlength="2" placeholder />
          </div>
        </div>
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{'*'}}</span>
            <span class="name-text">{{"图 标："}}</span>
          </div>
          <div class="image-box">
            <div
              class="image-grid"
              v-for="(image) of images"
              :key="image.id"
              :class="{active: selectedIcon == image}"
              @click="selectedIcon = image"
            >
              <img class="image-item" :src="image.url" />
              <img
                class="image-selected"
                v-if="selectedIcon == image"
                src="@media/expo/icon-select@2x.png"
              />
            </div>
          </div>
        </div>
    </template>
  </Dialog>
</template>

<script>
import oss from "@/utils/oss";
import { randomString, $formatDate } from "@/utils/tools";
import expoFristModuleService from "@api/expoFristModuleService";
import expoModuleService from "@api/expoModuleService"
import Dialog from "@/component/dialog/Dialog";
import { Loading, Message } from "element-ui";

export default {
  components: { Dialog },
  props: {
    funcConfirm: Function,
  },
  data() {
    return {
      headerTitle: "",
      confirmTitle: "",
      images: [],
      selectedIcon: {},
      params: {
        type:null
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {
    open() {
      const isOpen =
        this.$store.state.dialog.isOpenCreateFristModule ||
        this.$store.state.dialog.isOpenEditFristModule;
      return isOpen;
    },
    isCreate() {
      return this.$store.state.dialog.isOpenCreateFristModule;
    },
  },
  // 监控data中的数据变化
  watch: {
    open(value) {
      if (!value) {
        return;
      }
      if (this.isCreate) {
        this.headerTitle = "新建模块";
        this.confirmTitle = "创建";
        const item = this.$store.state.dialog.createModuleItem;
        this.params = {
          name: "",
          expo_uid: item.uid,
          image: "",
          sort: 0,
        };
      } else {
        this.headerTitle = "编辑模块";
        this.confirmTitle = "完成";
        const item = this.$store.state.dialog.editModuleItem;
        this.params = {
          name: item.name,
          uid: item.uid,
          image: item.image
        };
      }
    },
      params(value) {
      if (value.image !== undefined && value.image !== "") {
        const imageIndex = this.images.findIndex((item) => {
          return item.url === value.image;
        });
        console.log(12142)
        this.selectedIcon = this.images[imageIndex];
      }
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchImages();
    // 
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    handleClose() {
      const commitType = this.isCreate
        ? "dialog/CREATE_MODULE_FRIST_OPEN"
        : "dialog/EDIT_MODULE_FRIST_OPEN";
      this.$store.commit(commitType, false);
      this.selectedIcon=this.images[0]
    },
    handleConfirm() {
      if (!this.params.name) {
        Message.warning("请输入名称");
        // 
        return;
      }
      if (this.isCreate) {
        this.requestCreatModule();
        return;
      }
      this.editModule();
    },
    fetchImages() {
      expoFristModuleService
        .getCreateImage()
        .then((res) => {
          this.images = res.data.data;
          const defaultImage = this.images[0];
          if (defaultImage) {
            this.selectedIcon = defaultImage;
          }
        })
        .catch((res) => {});
    },
    editModule() {
      this.params.image = this.selectedIcon.url;
      let formData = new FormData();
      formData.append("uid", this.params.uid);
      formData.append("name", this.params.name);
      formData.append("image", this.params.image);
      console.log(123,'uid='+ formData.get("uid"),this.params.uid)
      this.requestEditModule(formData);
    },
    requestEditModule(formData, loadingInstance) {
      if (!loadingInstance) {
        loadingInstance = Loading.service({
          fullscreen: true,
          background: "rgba(0, 0, 0, 0.2)",
        });
      }
      const level='PARENT'
      expoModuleService
        .editModule(level, formData)
        .then((res) => {
          this.funcConfirm();
          this.handleClose();
          this.$nextTick(() => {
            loadingInstance.close();
          });
        })
        .catch((res) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
        });
    },
    requestCreatModule() {
      let loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, 0.2)",
      });
      this.params.image = this.selectedIcon.url;
      this.params.sort=this.$store.state.dialog.createModuleItem.sort;
      expoFristModuleService
        .createModule(this.params)
        .then((res) => {
          this.funcConfirm();
          this.handleClose();
          this.$nextTick(() => {
            loadingInstance.close();
          });
        })
        .catch((res) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
        });
    }
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="scss">
@import "@/style/scss/component/dialog/createModuleDialog.scss";
</style>
<style scoped lang="css">
.image-box{
  max-height: 371px !important;
}
</style>

